package com.gjt.clientSocket;

import java.io.*;
import java.net.*;

/**
 * Created with Intel IDEA.
 *
 *  WhoIs 协议: 客户端发送一个uhi车或者换行对结束搜索，服务器返回补丁数量的人的可读信息
 * @Auther: gjt
 * @Date: 2024/5/4 15:51
 */
public class WhoIs {
    private final static int DEFAULT_PORT = 43;
    private final static String DEFAULT_HOST = "whois.internic.org";

    private int port = DEFAULT_PORT;
    private InetAddress host;

    public WhoIs(InetAddress host, int port){
        this.host = host;
        this.port = port;
    }

    public WhoIs(InetAddress host){
        this(host,DEFAULT_PORT);
    }

    public WhoIs(String hostname, int port) throws UnknownHostException {
        this(InetAddress.getByName(hostname),port);
    }

    public WhoIs(String hostname) throws UnknownHostException {
        this(InetAddress.getByName(hostname), DEFAULT_PORT);
    }

    public WhoIs() throws UnknownHostException {
        this(DEFAULT_HOST, DEFAULT_PORT);
    }

    // 搜索的条目
    public enum SearchFor{
        ANY("Any"),NETWORK("Network"),PERSON("Person"),HOST("Host"),
        DOMAIN("Domain"),ORGANIZATION("Organization"),GROUP("Group"),GATEWAY("Gateway"),
        ASN("ASN");

        private String label;
        private SearchFor(String label){
            this.label = label;
        }
    }

    // 搜索的类别
    public enum SearchIn{
        ALL(""),NAME("Name"),MAILBOX("Mailbox"),HANDLE("!");
        private String label;
        private SearchIn(String label){
            this.label = label;
        }
    }


    public String lookUpNames(String target, SearchFor category, SearchIn group, boolean exactMatch) throws IOException {
        String suffix = "";
        if (!exactMatch) suffix = ".";

        String prefix = category.label + " " + group.label;
        String query = prefix + target + suffix;

        try (Socket socket = new Socket()) {

            SocketAddress address = new InetSocketAddress(host, port);
            socket.connect(address);

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "ASCII"));
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"));

            out.write(query + "\r\n");
            out.flush();

            StringBuilder response = new StringBuilder();
            String theLine = null;
            while ((theLine = in.readLine()) != null) {
                response.append(theLine);
                response.append("\r\n");
            }
            return response.toString();
        }
    }
    public InetAddress getHost(){
        return this.host;
    }

    public void setHost(String host) throws UnknownHostException {
        this.host = InetAddress.getByName(host);
    }
}
